package edu.put.sk.nrpp;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;

import edu.put.sk.nrpp.ospf.packet.OSPFPacketVersion2Type4;
import edu.put.sk.nrpp.ospf.packet.lsa.*;


public final class Router {
	public static Hashtable<String, Router> Dictionary = new Hashtable<String, Router>();
	private String name;
	
	private Router(String name){
		this.name=name;
	}
	
	public static synchronized Router getInstance(OSPFPacketVersion2Type4 ospf) {
		try{
			String name=ospf.getRouterID().toString();
			if (Dictionary.get(name)==null){
				Dictionary.put(name, new Router(name));
			}
			
			Dictionary.get(name).update(ospf);
	        return Dictionary.get(name);
		}catch(Exception e){
			return null;
		}
	}
	
	
	public ArrayList<Router> neighbor=new ArrayList<Router>();
	public ArrayList<NetworkMask> networks=new ArrayList<NetworkMask>();

	protected void updateLSAType1(LSAType1 dat) throws UnknownHostException{
		for(LSAType1Data d:dat.getLSAData()){
			NetworkMask nm=new NetworkMask(d.getLinkIDByBits(), d.getLinkDataBit());
			if(!networks.contains(nm))
				networks.add(nm);
		}
		
		for(Router r: Router.Dictionary.values()){
			for(NetworkMask nm: networks){
				for(NetworkMask nmr: r.networks){
					if(nm.equals(nmr)){
						r.neighbor.add(this);
						neighbor.add(r);
					}
				}
			}
		}
		
	}
	
	protected void update(OSPFPacketVersion2Type4 ospf) throws UnknownHostException{
		LSA[] data=ospf.getLSAData();
		for(LSA dat:data){
			if(dat instanceof LSAType1){
				updateLSAType1((LSAType1)dat);
			}
		}
	}
	
	
	public String getName() {
		return name;
	}
}
